package com.ny.controller;

import com.ny.entity.Device;
import com.ny.entity.Result;
import com.ny.service.DeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/devices")
public class DevicesController {

    @Autowired
    private DeviceService deviceService;

    // 查询所有的设备数据
    @GetMapping("/findAll")
    public Result findAllDevices(){
        try {
            List<Device> devices = deviceService.findAllDevices();
            return Result.success(devices);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("获取设备列表失败: " + e.getMessage());
        }
    }

    // 根据设备名称查询设备数据
    @GetMapping("/findByName")
    public Result findDeviceByName(@RequestParam String name){
        try {
            List<Device> devices = deviceService.findDevicesByName(name);
            return Result.success(devices);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询设备失败: " + e.getMessage());
        }
    }

    // 根据设备id删除设备数据
    @DeleteMapping("/delete/{id}")
    public Result deleteDeviceById(@PathVariable Integer id) {
        try {
            int result = deviceService.deleteDeviceById(id);
            if (result > 0) {
                return Result.success("设备删除成功");
            } else {
                return Result.error("设备删除失败，设备可能不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除设备失败: " + e.getMessage());
        }
    }

    // 根据设备名称模糊查询设备数据
    @GetMapping("/search")
    public Result findDevicesByNameContaining(@RequestParam String name){
        try {
            List<Device> devices = deviceService.findDevicesByName(name);
            return Result.success(devices);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("搜索设备失败: " + e.getMessage());
        }
    }
}